<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <!-- <el-form-item label="创建时间" prop="createTime">
      <el-input v-model="dataForm.createTime" placeholder="创建时间"></el-input>
    </el-form-item>
    <el-form-item label="修改时间" prop="updateTime">
      <el-input v-model="dataForm.updateTime" placeholder="修改时间"></el-input>
    </el-form-item> -->
      <!-- <el-form-item label="状态 1正常 0冻结" prop="status">
      <el-input v-model="dataForm.status" placeholder="状态 1正常 0冻结"></el-input>
    </el-form-item> -->
      <!-- <el-form-item label="商户" prop="shopId">
        <el-select v-model="dataForm.shopId" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.nikeName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="dataForm.productName"
          placeholder="产品名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="封面图" prop="images">
        <!-- <el-input v-model="dataForm.images" placeholder="图片"></el-input> -->

        <el-upload
          ref="upload"
          :action="uploadUrl"
          :limit="1"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="fileList"
          :on-exceed="handlexcedd"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog append-to-body :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="商品分类" prop="catagoryId">
        <!-- <el-input v-model="dataForm.catagoryId" placeholder="分类id 三级"></el-input> -->
        <div class="block">
          <el-cascader
            style="width: 300px"
            v-model="dataForm.catagoryId"
            :options="catagorys"
            :props="{ expandTrigger: 'hover' }"
            @change="handleChange"
          ></el-cascader>

          <!-- <el-cascader :options="catagorys" clearable>
            <template slot-scope="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader> -->
        </div>
      </el-form-item>
      <el-form-item label="参考价" prop="price">
        <el-input
          v-model="dataForm.price"
          placeholder="参考价"
          type="number"
        ></el-input>
      </el-form-item>
      <el-form-item label="产品参数" prop="productParam">
        <!-- <el-input v-model="dataForm.productParam" placeholder="产品参数 kv JSON"></el-input> -->
        <el-button
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click="addHeader()"
          >添加参数</el-button
        >
        <!-- 动态增加项目 -->
        <!-- 不止一个项目，用div包裹起来 -->
        <div v-for="(item, index) in testInfo.headers" :key="index">
          <div class="div-inline distance_style_10">
            <el-form-item style="margin-bottom: 20px">
              <el-input
                style="width: 100px"
                type="text"
                name="StartTime"
                v-model="item.title"
              />

              <el-input
                v-model="item.headerVal"
                style="width: 200px"
              ></el-input>
              <el-button @click.prevent="removeHeader(item, index)"
                >删除</el-button
              >
            </el-form-item>
          </div>
        </div>
      </el-form-item>
      <!-- <el-form-item label="分类名称 三级" prop="catagoryName">
      <el-input v-model="dataForm.catagoryName" placeholder="分类名称 三级"></el-input>
    </el-form-item> -->

      <el-form-item label="产品标签" prop="productLable">
        <el-select
          v-model="dataForm.productLable"
          multiple
          placeholder="请选择"
        >
          <el-option
            v-for="item in optionslable"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- <el-button
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click="addHeader1()"
          >添加标签</el-button
        >
      动态增加项目 -->
        <!-- 不止一个项目，用div包裹起来 -->
        <!-- <div v-for="(item, index) in productLables.headers" :key="index">
          <div class="div-inline distance_style_10">
            <el-form-item style="margin-bottom: 20px">
              <el-input
                style="width: 100px"
                type="text"
                name="StartTime"
                v-model="item.title"
              />
              <el-button @click.prevent="removeHeader1(item, index)"
                >删除</el-button
              >
            </el-form-item>
          </div>
        </div> -->
      </el-form-item>

      <!-- <el-form-item label="商户名称" prop="shopName">
      <el-input v-model="dataForm.shopName" placeholder="商户名称"></el-input>
    </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      testvalue: "",
      optionslable: [
        {
          value: "选项1",
          label: "黄金糕",
        },
      ],
      catagorys: [],
      productLables: {
        //del==false 不可删除
        headers: [{ title: "参数名", headerVal: "参数值", del: false }],
      },
      testInfo: {
        //del==false 不可删除
        headers: [{ title: "表亲", headerVal: "", del: false }],
      },
      fileList: [],
      uploadFile: {
        //上传的文件对象
        id: 0,
        url: "",
      },
      uploadUrl: this.$http.adornUrl(
        `/testing/file/uploadFile?token=${this.$cookie.get("token")}`
      ),
      dialogImageUrl: "",
      options: [],

      visible: false,
      dataForm: {
        id: 0,
        createTime: "",
        updateTime: "",
        status: "",
        images: "",
        catagoryId: "",
        productParam: "",
        catagoryName: "",
        productName: "",
        productLable: "",
        shopId: "",
        shopName: "",
        price: "",
      },
      dataRule: {
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" },
        ],
        status: [
          {
            required: true,
            message: "状态 1正常 0冻结不能为空",
            trigger: "blur",
          },
        ],
        images: [{ required: true, message: "图片不能为空", trigger: "blur" }],
        catagoryId: [
          { required: true, message: "分类id 三级不能为空", trigger: "blur" },
        ],
        productParam: [
          {
            required: true,
            message: "产品参数 kv JSON不能为空",
            trigger: "blur",
          },
        ],
        catagoryName: [
          { required: true, message: "分类名称 三级不能为空", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" },
        ],
        productLable: [
          {
            required: true,
            message: "产品标签 ,分割不能为空",
            trigger: "blur",
          },
        ],
        shopId: [
          { required: true, message: "商户Id不能为空", trigger: "blur" },
        ],
        shopName: [
          { required: true, message: "商户名称不能为空", trigger: "blur" },
        ],
        price: [
          { required: true, message: "商户名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    handleChange(data) {
      console.log("二级分类Id" + data[1]);
      //根据二级分类Id查询标签
      this.$http({
        url: this.$http.adornUrl("/testing/product/lable/" + data[1]),
        method: "get",
      }).then(({ data }) => {
        this.optionslable = data.data;
        console.log(data);
      });
    },
    handlexcedd() {
      this.$message.error("一次只能上传一张图片! ");
    },
    //图片上传成功的狗子
    handleSuccess(response, file, fileList) {
      if (response.code != 0) {
        //失败
        this.$message.error(response.msg);
        return;
      }
      console.log(this.uploadFile);
      this.uploadFile.id = file.uid;
      this.fileList = fileList;
      this.uploadFile.url = response.data.fileUrl;
      this.$message.success("上传成功！");
    },
    //文件删除
    handleRemove(file, fileList) {
      this.uploadFile = {};
      this.dataForm.images = null;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 递归判断列表，把最后的children设为undefined
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    getTree() {
      this.$http({
        url: this.$http.adornUrl("/testing/catagory/tree"),
        method: "get",
      }).then(({ data }) => {
        this.catagorys = data.tree;
        console.log("3242423423" + this.getTreeData(this.catagorys));
      });
    },
    addHeader1() {
      this.productLables.headers.push({
        title: "标签名",
      });
    },
    removeHeader1(item, index) {
      this.productLables.headers.splice(index, 1);
    },
    addHeader() {
      this.testInfo.headers.push({
        title: "参数名",
        headerVal: "参数值",
      });
    },
    removeHeader(item, index) {
      this.testInfo.headers.splice(index, 1);
    },
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/testing/shop/list"),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.options = data.page.list;
        }
      });
    },
    init(id) {
      //清空表单
      this.testInfo = {
        headers: [{ title: "参数名", headerVal: "参数值" }],
      };

      // this.productLables = { headers: [{ title: "标签名" }] };
      this.getTree();
      this.getDataList();
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.fileList = [];
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/testing/product/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams(),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.createTime = data.product.createTime;
              this.dataForm.updateTime = data.product.updateTime;
              this.dataForm.status = data.product.status;
              this.dataForm.images = data.product.images;
              this.dataForm.catagoryId = data.product.catagoryId.split(",");
              this.dataForm.productParam = data.product.productParam;
              this.dataForm.catagoryName = data.product.catagoryName;
              this.dataForm.productName = data.product.productName;
              this.dataForm.productLable = data.product.productLable.split(",");
              this.dataForm.shopId = data.product.shopId;
              this.dataForm.shopName = data.product.shopName;
              this.dataForm.price = data.product.price;
              //回显表单
              this.testInfo = JSON.parse(data.product.productParam);

              // this.productLables = JSON.parse(data.product.productLable);
              if (this.uploadFile != null) {
                this.uploadFile.url = this.dataForm.images;
              }
              //回显图片
              this.fileList.push({
                name: "",
                url: this.dataForm.images,
              });
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      console.log(this.dataForm.productLable);
      if (this.uploadFile != null) {
        this.dataForm.images = this.uploadFile.url; //设置图片
      }
      this.dataForm.productParam = JSON.stringify(this.testInfo); //自定义表单
      // this.dataForm.productLable = JSON.stringify(this.productLables); //自定义表单
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/testing/product/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              createTime: this.dataForm.createTime,
              updateTime: this.dataForm.updateTime,
              status: this.dataForm.status,
              images: this.dataForm.images,
              catagoryId: this.dataForm.catagoryId.toString(),
              productParam: this.dataForm.productParam,
              catagoryName: this.dataForm.catagoryName,
              productName: this.dataForm.productName,
              productLable: this.dataForm.productLable.toString(),
              shopId: this.dataForm.shopId,
              price: this.dataForm.price,
              shopName: this.dataForm.shopName,
            }),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
  },
};
</script>
